import java.util.Arrays;

public class myPriorityQueue {
    public int[] elem;
    public int usedSize;

    public myPriorityQueue() {
        this.elem = new int[20];
    }

    public void init(int[] a) {
        for (int i = 0; i < a.length; i++) {
            this.elem[i] = a[i];
            usedSize++;
        }
    }

    /**
     * 创建大根堆
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {

        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent, array.length);
        }
    }

    /**
     * @param parent 是每棵子树的根节点的下标
     * @param len    是每棵子树调整结束的结束条件
     *               向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int parent, int len) {
        int child = parent * 2 + 1;//左孩子
        while (child < len) {
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child++;
            }
            //此时child是最大的值

            //如果elem[child] > elem[parent],交换;如果小于,说明已经是大顶堆了就break
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int t = elem[i];
        elem[i] = elem[j];
        elem[j] = t;
    }

    /**
     * 入队：仍然要保持是大根堆
     *
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize - 1);
    }

    //向上调整
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                //如果elem[child] > elem[parent],说明已经是大根堆了,就不用再调整了,结束循环
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public int pollHeap() {
        if (isEmpty()) {
            return -1;
        }
        int ret = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        shiftDown(0, usedSize);
        return ret;
    }

    private boolean isEmpty() {
        return usedSize == 0;
    }

    public void show() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
